import { ref } from 'vue'
import { ElMessage } from 'element-plus'

export function useMapMarkers() {
  const markers = ref([])
  const jurisdictionPolygons = ref([])
  const stationsData = ref([])
  const markerPositions = ref([])
  const currentArrow = ref(null)

  const hiddenStations = new Set()
  const hiddenBuildings = new Set()
  
  // 性能优化：使用 Map 数据结构提高查找速度
  const markerCache = new Map()
  const getStationKey = (station) => {
    if (!station) return ''
    const name = station.工作站名称 || station.name || ''
    const lng = station.经度 ?? station.lng ?? ''
    const lat = station.纬度 ?? station.lat ?? ''
    return `${name}__${lng}__${lat}`
  }

  const getBuildingKey = (building) => {
    if (!building) return ''
    const name = building.楼宇名称 || building.name || ''
    const lng = building.经度 ?? building.lng ?? ''
    const lat = building.纬度 ?? building.lat ?? ''
    return `${name}__${lng}__${lat}`
  }

  const findStationMarkerByKey = (stationKey) => {
    return (
      markers.value.find(
        (marker) =>
          marker?.__markerType === 'station' && marker?.__stationKey === stationKey
      ) || null
    )
  }

  const findBuildingMarkerByKey = (buildingKey) => {
    return (
      markers.value.find(
        (marker) =>
          marker?.__markerType === 'building' && marker?.__buildingKey === buildingKey
      ) || null
    )
  }

  const hideStationMarker = (marker, station, mapInstance) => {
    const stationKey = getStationKey(station)
    if (!stationKey) return

    if (hiddenStations.has(stationKey)) return
    hiddenStations.add(stationKey)

    if (!marker) {
      marker = findStationMarkerByKey(stationKey)
    }

    if (marker) {
      marker.setMap(null)
      const index = markers.value.indexOf(marker)
      if (index !== -1) {
        markers.value.splice(index, 1)
      }
    }

    jurisdictionPolygons.value = jurisdictionPolygons.value.filter((polygon) => {
      if (polygon && polygon.__stationKey === stationKey) {
        polygon.setMap(null)
        return false
      }
      return true
    })

    stationsData.value = stationsData.value.filter((item) => {
      const key = item?.station ? getStationKey(item.station) : ''
      return key !== stationKey
    })

    if (mapInstance && mapInstance.closeInfoWindow) {
      mapInstance.closeInfoWindow()
    }

    ElMessage.success('已隐藏该工作站')
  }

  const hideBuildingMarker = (marker, building, mapInstance) => {
    const buildingKey = getBuildingKey(building)
    if (!buildingKey) return

    if (hiddenBuildings.has(buildingKey)) return
    hiddenBuildings.add(buildingKey)

    if (!marker) {
      marker = findBuildingMarkerByKey(buildingKey)
    }

    if (marker) {
      marker.setMap(null)
      const index = markers.value.indexOf(marker)
      if (index !== -1) {
        markers.value.splice(index, 1)
      }
    }

    if (mapInstance && mapInstance.closeInfoWindow) {
      mapInstance.closeInfoWindow()
    }

    ElMessage.success('已隐藏该楼宇')
  }

  
  // 工作站颜色映射表（为每个工作站分配独特颜色）
  const stationColorMap = new Map()
  let colorIndex = 0
  
  // 颜色生成器 - 为每个工作站生成独特的颜色
  const generateStationColor = (stationName, isCenter) => {
    if (stationColorMap.has(stationName)) {
      return stationColorMap.get(stationName)
    }
    
    // 为中心站和普通站使用不同的色相范围
    const centerHues = [260, 210, 340, 180, 30, 290, 150, 350, 200, 310, 120, 10, 240, 170, 320]  // 中心站：紫、蓝、粉、青、橙等
    const normalHues = [140, 100, 50, 80, 160, 70, 190, 40, 110, 130, 60, 170, 90, 180, 120]      // 普通站：绿、黄绿等
    
    const hues = isCenter ? centerHues : normalHues
    const hue = hues[colorIndex % hues.length]
    
    // 增加饱和度，降低亮度，让颜色更深更鲜艳
    const saturation = isCenter ? 80 : 70
    const lightness = isCenter ? 50 : 45
    
    const color = {
      main: `hsl(${hue}, ${saturation}%, ${lightness}%)`,        // 主色
      light: `hsl(${hue}, ${saturation}%, ${lightness + 35}%)`,  // 浅色（背景）
      dark: `hsl(${hue}, ${saturation + 10}%, ${lightness - 10}%)`, // 深色（边框）
      hue: hue,
      saturation: saturation,
      lightness: lightness
    }
    
    stationColorMap.set(stationName, color)
    colorIndex++
    
    return color
  }
  
  // 检测矩形重叠（增强版，更准确的碰撞检测）
  const isOverlapping = (rect1, rect2, padding = 3) => {
    return !(
      rect1.right + padding < rect2.left || 
      rect1.left - padding > rect2.right || 
      rect1.bottom + padding < rect2.top || 
      rect1.top - padding > rect2.bottom
    )
  }
  
  // 计算标签矩形位置
  const getLabelRect = (map, lngLat, width, height, offsetX = 0, offsetY = 0) => {
    const pixel = map.lngLatToContainer(lngLat)
    return {
      left: pixel.x + offsetX - width / 2,
      right: pixel.x + offsetX + width / 2,
      top: pixel.y + offsetY - height,
      bottom: pixel.y + offsetY,
      centerX: pixel.x + offsetX,
      centerY: pixel.y + offsetY - height / 2
    }
  }
  
  // 智能寻找标签最佳位置（性能优化版）
  const findBestLabelPosition = (map, lngLat, labelWidth, labelHeight) => {
    // 快速路径：如果标记很少，使用简化算法（默认在上方）
    if (markerPositions.value.length < 3) {
      const defaultPos = { x: 0, y: -35 }
      const rect = getLabelRect(map, lngLat, labelWidth, labelHeight, defaultPos.x, defaultPos.y)
      markerPositions.value.push(rect)
      return { offset: defaultPos, needsLine: false }
    }
    
    // 增强版位置数组：更多候选位置，更智能的分布
    const positions = [
      // 第1层：紧贴点位（35-45px）
      { x: 0, y: -35 },      { x: -45, y: 0 },     { x: 45, y: 0 },
      { x: -35, y: -30 },    { x: 35, y: -30 },
      
      // 第2层：中等距离（50-65px）
      { x: 0, y: -55 },      { x: -60, y: 0 },     { x: 60, y: 0 },
      { x: -50, y: -25 },    { x: 50, y: -25 },    { x: -45, y: -45 },   { x: 45, y: -45 },
      
      // 第3层：较远距离（70-85px）
      { x: 0, y: -75 },      { x: -75, y: 0 },     { x: 75, y: 0 },
      { x: -65, y: -35 },    { x: 65, y: -35 },    { x: -60, y: -60 },   { x: 60, y: -60 },
      
      // 第4层：更远距离（90-100px）
      { x: 0, y: -95 },      { x: -90, y: 0 },     { x: 90, y: 0 },
      { x: -80, y: -50 },    { x: 80, y: -50 },    { x: -70, y: -70 },   { x: 70, y: -70 },
      
      // 第5层：下方位置（尽量避免，但作为后备）
      { x: 0, y: 45 },       { x: -35, y: 35 },    { x: 35, y: 35 },
      { x: 0, y: 65 },       { x: -55, y: 45 },    { x: 55, y: 45 },
      { x: -45, y: 60 },     { x: 45, y: 60 },
      
      // 第6层：极远距离（100+px，作为最后备选）
      { x: 0, y: -110 },     { x: -105, y: 0 },    { x: 105, y: 0 },
      { x: -90, y: -90 },    { x: 90, y: -90 },    { x: 0, y: 85 }
    ]
    
    // 检查所有候选位置
    for (let i = 0; i < positions.length; i++) {
      const pos = positions[i]
      const rect = getLabelRect(map, lngLat, labelWidth, labelHeight, pos.x, pos.y)
      
      // 检查是否与现有标记重叠
      let hasOverlap = false
      
      // 重要：检查所有已有标记，而不是只检查最近的
      // 在密集区域，远处的标记也可能造成重叠
      for (let j = 0; j < markerPositions.value.length; j++) {
        // 使用更小的 padding (1px) 允许标签更紧密
        if (isOverlapping(rect, markerPositions.value[j], 1)) {
          hasOverlap = true
          break
        }
      }
      
      if (!hasOverlap) {
        markerPositions.value.push(rect)
        return { offset: pos, needsLine: false }
      }
    }
    
    // 如果所有候选位置都被占用，使用动态偏移策略
    // 根据已有标记数量，螺旋式向外扩展
    const count = markerPositions.value.length
    const angle = (count * 137.5) % 360  // 黄金角度，避免聚集
    const radius = 40 + Math.floor(count / 8) * 15  // 螺旋半径递增
    const radians = (angle * Math.PI) / 180
    const dynamicPos = {
      x: Math.round(Math.cos(radians) * radius),
      y: Math.round(Math.sin(radians) * radius) - 20  // 略微向上偏移
    }
    
    const rect = getLabelRect(map, lngLat, labelWidth, labelHeight, dynamicPos.x, dynamicPos.y)
    markerPositions.value.push(rect)
    return { offset: dynamicPos, needsLine: false }
  }
  
  // 批量添加标记（性能优化）
  const addMarkersInBatch = async (map, items, type) => {
    const AMap = window.AMap
    const batchMarkers = []
    
    for (const item of items) {
      const marker = type === 'station' 
        ? await createStationMarker(map, item) 
        : await createBuildingMarker(map, item)
      
      if (marker) {
        batchMarkers.push(marker)
      }
    }
    
    // 批量添加到地图，减少重绘次数
    markers.value.push(...batchMarkers)
    return batchMarkers
  }
  
  // 创建工作站标记（工作站标签和管辖范围使用相同的独特颜色）
  const createStationMarker = async (map, station, showLabel = true, labelPosition = 'center') => {
    const stationKey = getStationKey(station)
    if (!stationKey || hiddenStations.has(stationKey)) {
      return null
    }

    const isCenter = station.工作站类型 === '中心站'
    const typeLabel = isCenter ? '中心站' : '普通站'
    
    // 为管辖范围生成独特颜色
    const stationColors = generateStationColor(station.工作站名称, isCenter)
    
    // 工作站标签使用管辖范围相同的颜色
    const labelColor = stationColors.main
    const labelBorderColor = stationColors.dark
    
    // 使用完整的工作站名称，确保包含"楼宇工作站"
    let stationName = station.工作站名称 || ''
    
    // 如果名称中没有"楼宇工作站"，则添加
    if (stationName && !stationName.includes('楼宇工作站')) {
      // 如果名称以"工作站"结尾，替换为"楼宇工作站"
      if (stationName.endsWith('工作站')) {
        stationName = stationName.replace(/工作站$/, '楼宇工作站')
      } else {
        // 否则直接添加"楼宇工作站"
        stationName = stationName + '楼宇工作站'
      }
    }
    
    // 根据名称长度动态调整字体大小（减小字体，减少遮挡）
    const fontSize = stationName.length > 12 ? 7 : stationName.length > 8 ? 8 : 9
    const labelWidth = Math.max(stationName.length * fontSize + 26, 70)
    
    // 醒目的标签 - 工作站标签（3D立体效果）
    const labelContent = `
      <div style="
        text-align:center;
        white-space:nowrap;
        pointer-events:auto;
        background:linear-gradient(135deg, ${labelColor} 0%, ${labelBorderColor} 100%);
        color:white;
        padding:4px 10px;
        border-radius:6px;
        font-size:${fontSize}px;
        font-weight:bold;
        box-shadow:
          0 4px 8px rgba(0,0,0,0.3),
          0 2px 4px rgba(0,0,0,0.2),
          inset 0 1px 0 rgba(255,255,255,0.3),
          inset 0 -1px 0 rgba(0,0,0,0.2);
        border:1px solid rgba(255,255,255,0.2);
        transform:translateZ(0);
      ">
        <div style="font-size:${fontSize - 1}px;opacity:0.95;margin-bottom:1px;text-shadow:0 1px 2px rgba(0,0,0,0.3);">${typeLabel}</div>
        <div style="font-size:${fontSize + 1}px;letter-spacing:0.3px;text-shadow:0 1px 3px rgba(0,0,0,0.4);">${stationName}</div>
      </div>
    `
    
    const lngLat = [parseFloat(station.经度), parseFloat(station.纬度)]
    
    const AMap = window.AMap
    
    // 根据 labelPosition 决定标签位置
    // 'center': 正上方（默认）
    // 'left': 左侧
    // 'right': 右侧
    let labelOffset
    if (labelPosition === 'left') {
      // 左侧：标签在点的左边，标签右边缘对齐到点的左侧
      // 偏移量 = -(标签宽度/2 + 点与标签间距)
      labelOffset = new AMap.Pixel(-labelWidth / 2 - 20, -25)
    } else if (labelPosition === 'right') {
      // 右侧：标签在点的右边，标签左边缘对齐到点的右侧
      // 偏移量 = 标签宽度/2 + 点与标签间距
      labelOffset = new AMap.Pixel(labelWidth / 2 + 20, -25)
    } else {
      // 默认：正上方
      labelOffset = new AMap.Pixel(0, -40)
    }
    
    const marker = new AMap.Marker({
      position: lngLat,
      title: stationName,  // 使用完整的工作站名称（包含"楼宇工作站"）
      label: {
        content: labelContent,
        offset: labelOffset,
        direction: 'center'
      },
      offset: new AMap.Pixel(-12, -12),
      icon: new AMap.Icon({
        size: new AMap.Size(24, 24),
        image: 'data:image/svg+xml;base64,' + btoa(`
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
            <circle cx="12" cy="12" r="10" fill="${labelColor}" opacity="0.9" stroke="white" stroke-width="2"/>
            <circle cx="12" cy="12" r="6" fill="white" opacity="0.4"/>
          </svg>
        `),
        imageSize: new AMap.Size(24, 24)
      })
    })
    
    // 优化事件处理
    marker.__markerType = 'station'
    marker.__stationKey = stationKey

    marker.on('click', () => {
      showStationInfo(map, station, marker)
    })
    
    marker.setMap(map)
    
    // 将marker添加到数组，便于后续清除
    markers.value.push(marker)
    
    // 存储工作站数据（标签和管辖范围使用相同的独特颜色）
    stationsData.value.push({
      name: station.工作站名称,
      lng: station.经度,
      lat: station.纬度,
      labelColor,                 // 工作站标签颜色（与管辖范围相同）
      jurisdictionColor: stationColors.main,  // 管辖范围颜色（独特）
      colors: stationColors,                  // 保存完整的颜色对象
      station,
      stationKey
    })
    
    return marker
  }
  
  // 创建楼宇标记（使用所属工作站的管辖范围颜色）
  const createBuildingMarker = async (map, building) => {
    const buildingKey = getBuildingKey(building)
    if (!buildingKey || hiddenBuildings.has(buildingKey)) {
      return null
    }

    const buildingName = building.楼宇名称 || ''
    
    // 查找楼宇所属工作站的颜色
    const stationName = building.所属工作站 || ''
    const isCenter = building.工作站类型 === '中心站'
    
    // 使用所属工作站的管辖范围颜色
    const stationColors = generateStationColor(stationName, isCenter)
    const color = stationColors.main
    
    // 根据名称长度动态调整（减小字体，减少遮挡）
    const fontSize = buildingName.length > 10 ? 7 : 8
    const labelWidth = Math.max(buildingName.length * fontSize + 14, 50)
    
    const lngLat = [parseFloat(building.经度), parseFloat(building.纬度)]
    const bestPos = findBestLabelPosition(map, lngLat, labelWidth, 24)
    
    // 楼宇标签（3D立体效果）
    const labelContent = `<div style="
      background:linear-gradient(135deg, ${color} 0%, ${stationColors.dark} 100%);
      color:white;
      padding:2px 6px;
      border-radius:4px;
      font-size:${fontSize}px;
      font-weight:bold;
      white-space:nowrap;
      box-shadow:
        0 3px 6px rgba(0,0,0,0.25),
        0 1px 3px rgba(0,0,0,0.15),
        inset 0 1px 0 rgba(255,255,255,0.25),
        inset 0 -1px 0 rgba(0,0,0,0.15);
      border:1px solid rgba(255,255,255,0.15);
      text-shadow:0 1px 2px rgba(0,0,0,0.3);
      pointer-events:auto;
      transform:translateZ(0);
    ">${buildingName}</div>`
    
    const AMap = window.AMap
    
    const marker = new AMap.Marker({
      position: lngLat,
      title: building.楼宇名称,
      label: {
        content: labelContent,
        offset: new AMap.Pixel(bestPos.offset.x, bestPos.offset.y),
        direction: 'center'
      },
      icon: new AMap.Icon({
        size: new AMap.Size(12, 12),
        image: 'data:image/svg+xml;base64,' + btoa(`
          <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12">
            <circle cx="6" cy="6" r="5" fill="${color}" opacity="0.85" stroke="white" stroke-width="1.5"/>
            <circle cx="6" cy="6" r="2.5" fill="white" opacity="0.6"/>
          </svg>
        `),
        imageSize: new AMap.Size(12, 12)
      }),
      offset: new AMap.Pixel(-6, -6)
    })
    
    marker.__markerType = 'building'
    marker.__buildingKey = buildingKey

    marker.on('click', () => {
      showBuildingInfo(map, building, marker)
    })
    
    marker.setMap(map)
    
    // 将marker添加到数组，便于后续清除
    markers.value.push(marker)
    
    return marker
  }
  
  // 添加工作站标记
  const addStationMarker = async (map, station, showLabel = true, labelPosition = 'center') => {
    if (hiddenStations.has(getStationKey(station))) {
      return null
    }

    if (!showLabel) {
      // 如果不显示标签，使用更简单的标记
      return createSimpleMarker(map, station, 'station')
    }
    return createStationMarker(map, station, showLabel, labelPosition)
  }
  
  // 添加楼宇标记
  const addBuildingMarker = async (map, building, showLabel = true) => {
    if (hiddenBuildings.has(getBuildingKey(building))) {
      return null
    }

    if (!showLabel) {
      return createSimpleMarker(map, building, 'building')
    }
    return createBuildingMarker(map, building)
  }
  
  // 创建简单标记（不显示标签时使用，性能更好）
  const createSimpleMarker = (map, item, type) => {
    const isStation = type === 'station'
    const isCenter = isStation && item.工作站类型 === '中心站'

    const key = isStation ? getStationKey(item) : getBuildingKey(item)
    if (!key) return null
    if (isStation) {
      if (hiddenStations.has(key)) return null
    } else {
      if (hiddenBuildings.has(key)) return null
    }
    
    // 工作站和楼宇都使用管辖范围颜色
    let color
    let stationColors = null
    if (isStation) {
      // 工作站标记使用管辖范围颜色
      stationColors = generateStationColor(item.工作站名称, isCenter)
      color = stationColors.main
    } else {
      // 楼宇使用所属工作站的管辖范围颜色
      const stationName = item.所属工作站 || ''
      const stationIsCenter = item.工作站类型 === '中心站'
      stationColors = generateStationColor(stationName, stationIsCenter)
      color = stationColors.main
    }
    
    const size = isStation ? 24 : 18  // 增大楼宇点位，从12增加到18
    
    const AMap = window.AMap
    const lngLat = [parseFloat(item.经度), parseFloat(item.纬度)]
    
    const marker = new AMap.Marker({
      position: lngLat,
      title: isStation ? item.工作站名称 : item.楼宇名称,
      icon: new AMap.Icon({
        size: new AMap.Size(size, size),
        image: 'data:image/svg+xml;base64,' + btoa(`
          <svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}">
            <circle cx="${size/2}" cy="${size/2}" r="${size/2-2}" fill="${color}" opacity="0.85" stroke="white" stroke-width="2"/>
          </svg>
        `),
        imageSize: new AMap.Size(size, size)
      }),
      offset: new AMap.Pixel(-size/2, -size/2)
    })
    
    marker.__markerType = isStation ? 'station' : 'building'
    if (isStation) {
      marker.__stationKey = key
    } else {
      marker.__buildingKey = key
    }

    marker.on('click', () => {
      if (isStation) {
        showStationInfo(map, item, marker)
      } else {
        showBuildingInfo(map, item, marker)
      }
    })
    
    marker.setMap(map)
    
    // 将marker添加到数组，便于后续清除
    markers.value.push(marker)
    
    if (isStation) {
      stationsData.value.push({
        name: item.工作站名称,
        lng: item.经度,
        lat: item.纬度,
        labelColor: color,                      // 工作站标签颜色（固定：紫/绿）
        jurisdictionColor: stationColors.main,  // 管辖范围颜色（独特）
        colors: stationColors,                  // 保存完整的颜色对象
        station: item,
        stationKey: key
      })
    }
    
    return marker
  }
  
  // 显示工作站信息（优化内容长度）
  const showStationInfo = (map, station, marker = null) => {
    const stationKey = getStationKey(station)
    if (hiddenStations.has(stationKey)) {
      ElMessage.info('该工作站已被隐藏')
      return
    }

    if (!marker) {
      marker = findStationMarkerByKey(stationKey)
    }

    const buildings = station.覆盖楼宇列表 || []
    
    let buildingListHtml = ''
    if (buildings.length > 0) {
      // 最多显示前 20 个，提高性能
      const displayBuildings = buildings.slice(0, 20)
      const hasMore = buildings.length > 20
      
      buildingListHtml = `
        <div style="margin-top:8px;padding-top:8px;border-top:1px solid #eee;">
          <p style="font-size:11px;color:#667eea;font-weight:bold;margin-bottom:4px;">📋 管辖楼宇：</p>
          <div style="max-height:120px;overflow-y:auto;font-size:10px;line-height:1.6;">
            ${displayBuildings.map((b, i) => `
              <div style="padding:1px 0;color:#555;">${i + 1}. ${b.楼宇名称 || '未命名'}</div>
            `).join('')}
            ${hasMore ? `<div style="padding:2px 0;color:#999;">...还有 ${buildings.length - 20} 个楼宇</div>` : ''}
          </div>
        </div>
      `
    }
    
    const hideButtonId = `hide-station-btn-${Date.now()}-${Math.floor(Math.random() * 1000)}`

    const content = `
      <div style="padding:8px;max-width:280px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
          <div style="color:#667eea;font-size:13px;font-weight:bold;line-height:1.4;">
            ${station.工作站名称}
          </div>
          <button id="${hideButtonId}" style="
            background:#ef4444;
            color:#fff;
            border:none;
            border-radius:4px;
            padding:4px 8px;
            font-size:10px;
            cursor:pointer;
            transition:all 0.2s ease;
          ">隐藏该点</button>
        </div>
        <p style="font-size:11px;color:#666;margin:4px 0;">
          <strong>类型:</strong> ${station.工作站类型}
        </p>
        <p style="font-size:11px;color:#666;margin:4px 0;">
          <strong>所属街道:</strong> ${station.所属街道}
        </p>
        <p style="font-size:11px;color:#666;margin:4px 0;">
          <strong>覆盖楼宇:</strong> ${station.覆盖楼宇数量} 个
        </p>
        ${buildingListHtml}
      </div>
    `
    
    const AMap = window.AMap
    const infoWindow = new AMap.InfoWindow({
      content: content,
      offset: new AMap.Pixel(0, -30)
    })
    
    infoWindow.on('open', () => {
      const button = document.getElementById(hideButtonId)
      if (button) {
        button.addEventListener(
          'click',
          () => {
            hideStationMarker(marker, station, map)
          },
          { once: true }
        )
      }
    })

    infoWindow.open(map, [station.经度, station.纬度])
  }
  
  // 显示楼宇信息
  const showBuildingInfo = (map, building, marker = null) => {
    const buildingKey = getBuildingKey(building)
    if (hiddenBuildings.has(buildingKey)) {
      ElMessage.info('该楼宇已被隐藏')
      return
    }

    if (!marker) {
      marker = findBuildingMarkerByKey(buildingKey)
    }

    const hideButtonId = `hide-building-btn-${Date.now()}-${Math.floor(Math.random() * 1000)}`

    const content = `
      <div style="padding:8px;max-width:260px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
          <div style="color:#ed8936;font-size:13px;font-weight:bold;line-height:1.4;">
            ${building.楼宇名称}
          </div>
          <button id="${hideButtonId}" style="
            background:#ef4444;
            color:#fff;
            border:none;
            border-radius:4px;
            padding:4px 8px;
            font-size:10px;
            cursor:pointer;
            transition:all 0.2s ease;
          ">隐藏该点</button>
        </div>
        <p style="font-size:11px;color:#666;margin:4px 0;">
          <strong>地址:</strong> ${building.楼宇地址}
        </p>
        <p style="font-size:11px;color:#666;margin:4px 0;">
          <strong>所属工作站:</strong> ${building.所属工作站}
        </p>
        <p style="font-size:11px;color:#666;margin:4px 0;">
          <strong>所属街道:</strong> ${building.所属街道}
        </p>
        ${building.重点企业类型 ? `<p style="font-size:10px;color:#e53e3e;margin-top:6px;padding:4px;background:#fff5f5;border-radius:3px;"><strong>⭐ ${building.重点企业类型}</strong></p>` : ''}
      </div>
    `
    
    const AMap = window.AMap
    const infoWindow = new AMap.InfoWindow({
      content: content,
      offset: new AMap.Pixel(0, -10)
    })
    
    infoWindow.on('open', () => {
      const button = document.getElementById(hideButtonId)
      if (button) {
        button.addEventListener(
          'click',
          () => {
            hideBuildingMarker(marker, building, map)
          },
          { once: true }
        )
      }
    })

    infoWindow.open(map, [building.经度, building.纬度])
  }
  
  // 绘制管辖范围（使用独特颜色）
  const drawJurisdiction = (map, station) => {
    const stationKey = getStationKey(station)
    if (hiddenStations.has(stationKey)) return

    const buildings = station.覆盖楼宇列表 || []
    
    if (buildings.length === 0) return
    if (!station.经度 || !station.纬度) return
    
    const centerLng = parseFloat(station.经度)
    const centerLat = parseFloat(station.纬度)
    
    let minLng = centerLng, maxLng = centerLng
    let minLat = centerLat, maxLat = centerLat
    let validBuildingCount = 0
    
    buildings.forEach(building => {
      if (building.经度 && building.纬度 && 
          !isNaN(parseFloat(building.经度)) && !isNaN(parseFloat(building.纬度))) {
        const lng = parseFloat(building.经度)
        const lat = parseFloat(building.纬度)
        
        minLng = Math.min(minLng, lng)
        maxLng = Math.max(maxLng, lng)
        minLat = Math.min(minLat, lat)
        maxLat = Math.max(maxLat, lat)
        validBuildingCount++
      }
    })
    
    if (validBuildingCount === 0) return
    
    const lngPadding = (maxLng - minLng) * 0.08 || 0.002
    const latPadding = (maxLat - minLat) * 0.08 || 0.002
    
    minLng -= lngPadding
    maxLng += lngPadding
    minLat -= latPadding
    maxLat += latPadding
    
    // 获取该工作站的独特颜色
    const isCenter = station.工作站类型 === '中心站'
    const stationColors = generateStationColor(station.工作站名称, isCenter)
    const strokeColor = stationColors.main
    const fillColor = stationColors.main
    
    const AMap = window.AMap
    const rectangle = new AMap.Rectangle({
      bounds: new AMap.Bounds([minLng, minLat], [maxLng, maxLat]),
      strokeColor: strokeColor,
      strokeWeight: 0,           // 去掉边框
      strokeOpacity: 0,          // 边框完全透明
      strokeStyle: 'solid',
      fillColor: fillColor,
      fillOpacity: 0.18,         // 增加透明度，让颜色更深
      zIndex: 50
    })
    
    // 简化事件处理
    rectangle.__stationKey = stationKey

    rectangle.on('click', () => {
      const marker = findStationMarkerByKey(stationKey)
      showStationInfo(map, station, marker)
    })
    
    rectangle.setMap(map)
    jurisdictionPolygons.value.push(rectangle)
  }
  
  // 创建指向工作站的箭头
  const createArrowToStation = (map, stationIndex, mapData) => {
    const station = stationsData.value[stationIndex]
    if (!station || !station.lng || !station.lat) return null
    if (station.stationKey && hiddenStations.has(station.stationKey)) return null
    
    const AMap = window.AMap
    const overlayRightX = 470
    const overlayMidY = 200
    
    const startPixel = { x: overlayRightX, y: overlayMidY }
    const startLngLat = map.containerToLngLat(new AMap.Pixel(startPixel.x, startPixel.y))
    
    const endLngLat = [parseFloat(station.lng), parseFloat(station.lat)]
    
    const polyline = new AMap.Polyline({
      path: [[startLngLat.lng, startLngLat.lat], endLngLat],
      strokeColor: station.jurisdictionColor || station.labelColor || '#667eea',  // 使用管辖范围颜色
      strokeWeight: 3,
      strokeOpacity: 0.85,
      strokeStyle: 'solid',
      showDir: true,
      zIndex: 1000
    })
    
    polyline.setMap(map)
    map.setZoomAndCenter(15, endLngLat)
    
    if (station.station) {
      const marker = station.stationKey
        ? findStationMarkerByKey(station.stationKey)
        : null
      showStationInfo(map, station.station, marker)
    }
    
    return polyline
  }
  
  // 清除所有标记（批量操作，极速版）
  const clearAll = (map) => {
    // 简化日志，减少输出
    // console.log('🧹 清除地图标记...', {
    //   markers: markers.value.length,
    //   polygons: jurisdictionPolygons.value.length
    // })
    
    // 使用map.clearMap()一次性清除所有覆盖物（最快）
    if (map && map.clearMap) {
      map.clearMap()
    }
    
    // 快速清空数组（不遍历）
    markers.value = []
    jurisdictionPolygons.value = []
    currentArrow.value = null
    stationsData.value = []
    markerPositions.value = []
    markerCache.clear()
    
    // 清空颜色映射，重置颜色索引
    stationColorMap.clear()
    colorIndex = 0
    
    // console.log('✅ 地图标记清除完成')
  }
  
  return {
    markers,
    stationsData,
    currentArrow,
    addStationMarker,
    addBuildingMarker,
    drawJurisdiction,
    clearAll,
    createArrowToStation,
    addMarkersInBatch
  }
}
